jQuery(document).ready(function(){
	//for validation
	if($('.form').length)
		jQuery(".form").validationEngine();
	
	//watermark
	//$('#keyword').watermark('watermark', $('#keyword').attr('id'));
	
	//form submit
	$('#form-submit').click(function(){	
		if($('.form').validationEngine('validate'))
		{			
			showLoader('#main');
			var action = root + module + '/' + $("input[name='action']").val();
			var dt = $('.form').serializeArray();
			
			if($('input[name=item]').val())
				dt[dt.length] = {name: 'item', value: $('input[name=item]').val()}

			$.ajax({
			   type: 'POST',
			   url: action,
			   data: dt,
			   dataType: 'json',
			   success: function(data){
					hideLoader();
					if(data.return=="success")						
						successFunction();
					else if(data.return=="error")
						errorFunction();
				},
			   error: function () { onError(); hideLoader(); }
			 });
		}
	});
	
	//load view data
	if($('input[name=item]').val())
	{
		showLoader('#main');
		var action = root + module + '/viewitem';
		var dt = {item: $('input[name=item]').val()}
		$.ajax({
		   type: 'POST',
		   url: action,
		   data: dt,
		   dataType: 'json',
		   success: function(data){
				procJSON.view(data);
				hideLoader();
				if(data.return=="success")						
					successFunction();
				else if(data.return=="error")
					errorFunction();
			},
		   error: function () { onError(); hideLoader(); }
		 });
	}
	
	//set datepicker
	if($('.datep').length)
		$('.datep').datepicker({ inline: true });
	
	//set datepicker
	if($('.timep').length)
		$('.timep').timepicker({ inline: true });
	
	//search functionality
	$('#search-flexigrid').click(function(){
		var dt = [{name:'squery',value:$('#keyword').val()}];
		$('.listFlex').flexOptions({params:dt}).flexReload();
	});
	$('#keyword').keyup(function(event){
		if(event.keyCode==13)
			$('#search-flexigrid').trigger('click');
	});
	$('#clear-flexigrid').click(function(){
		$('#keyword').val('');
		var dt = [{name:'squery',value:$('#keyword').val()}];
		$('.listFlex').flexOptions({params:dt}).flexReload();
	});
	
	//search functionality dialog
	$('#search-flexigrid').click(function(){
		var dt = [{name:'squery',value:$('#keyword').val()}];
		$('.dialogFlex').flexOptions({params:dt}).flexReload();
	});
	$('#clear-flexigrid').click(function(){
		$('#keyword').val('');
		var dt = [{name:'squery',value:$('#keyword').val()}];
		$('.dialogFlex').flexOptions({params:dt}).flexReload();
	});
	
	
	//dialog
	$('a[id=dialog-close]').click(function(){
		$('.dialog').dialog('close');
	});
	
});

//generate random password
(function($) {

  $.generateRandomPassword = function(limit) {
  
    limit = limit || 8;
  
    var password = '';
  
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,./<>?!@#$%^&*()';
  
    var list = chars.split('');
    var len = list.length, i = 0;
    
    do {
    
      i++;
    
      var index = Math.floor(Math.random() * len);
      
      password += list[index];
    
    } while(i < limit);
    
    return password;
 
  };


})(jQuery);

function successFunction()
{
	if($('input[name=action]').val()=="additem")//success on add
	{
		if(confirm("Do you want to add another?"))
		{
			//reset
			$('.form input').val("");
			$('.form select').val("");			
			$('.form textarea').val("");
		}
		else
			location.href = root + module + "/manage.html";
	}
	else if($('input[name=profile]').val()=="true")//success on profile edit
	{
		alert("Profile saved.");
	}
	else if($('input[name=action]').val()=="updateitem")//success on edit
	{
		if(confirm("Update successful. Go back to the list?"))
			location.href = root + module + "/manage.html";
	}
	//hide validation
	$('.form').validationEngine('hide');
}

function errorFunction()
{
	if($('input[name=action]').val()=="additem")//error on add
	{
		
	}
	else if($('input[name=action]').val()=="updateitem")//error on edit
	{
		
	}
}


function onError()
{
	alert('There was an error encountered. Please try refreshing your page.');
}


function showLoader(element)
{
	var left = $(element).offset().left;
	//var left = 0;
	var width = $(element).width();
	var top = $(element).offset().top;
	//var top = 0;
	var height = $(element).height();

	$('#loader').css('left',(left-16)+(width/2));
	$('#loader').css('top',(top-16)+(height/2));
	$('#loader').show();
	$('div[id=overlay]').show();
}
function showLoaderSmall(element)
{
	var left = $(element).offset().left;
	//var left = 0;
	var width = $(element).width();
	var top = $(element).offset().top;
	//var top = 0;
	var height = $(element).height();

	$('#loader-small').css('left',(left-8)+(width/2));
	$('#loader-small').css('top',(top-8)+(height/2));
	$('#loader-small').show();
	//$('#overlay-small').show();
}
function hideLoader()
{
	$('#loader').hide();
	$('div[id=overlay]').hide();
}
function hideLoaderSmall()
{
	$('#loader-small').hide();
	//$('#overlay').hide();
}

function viewItem(celDiv,id)
{
	celDiv.innerHTML = '<a href="'+root + module + '/edit/' + id +'.html" id="'+id+'" class="fview" title="View"></a>';
	// $(celDiv).click(function(){
		// location. href = root + module + '/edit/' + id + '.html';
	// });
} 

function addItem()
{
	location.href = root + module + '/add.html';
}

function deleteItem()
{
	if($('.listFlex .trSelected').length)
	{
		if(confirm('Are you sure you want to delete selected item/s?'))
		{
			showLoader('#main');
			var data = new Array();
			var count = 0;
			$('.listFlex .trSelected .fview').each(function(){
				data[count] = $(this).attr('id');
				count++;
			});			
			var action = root + module + '/deleteitem';
			var dt = {items: data};

			$.ajax({
			   type: 'POST',
			   url: action,
			   data: dt,
			   dataType: 'json',
			   success: function(data){
					hideLoader();
					$('.listFlex').flexReload();
				},
			   error: function () { onError(); hideLoader(); }
			 });
		}
	}
	else
	{
		alert("Please select item/s to delete.");
	}
}


var procJSON = {
	'form' : false
	,'json' : false
	,'rs' : ''
	,'view' : function (json)
	{
		var edata = json[0];	
		$.each( edata, function(i, n){
			// if ($('input[name=' + i + ']').length)						
					// $('input[name=' + i + ']').val('');
			// if ($('select[name=' + i + ']').length)						
					// $('select[name=' + i + ']').val('');
			// if ($('textarea[name=' + i + ']').length)
			// {						
					// $('textarea[name=' + i + ']').val('');						
						// tinyMCE.execCommand('mceRemoveControl', false, i);
			// }
			
			//set rules
			if(i=='password') n = ''; //password
			if(n=='0000-00-00 00:00:00') n = ''; //datetime
			
			if ($('input[id=' + i + ']').length)						
					$('input[id=' + i + ']').val(n);
			if ($('select[id=' + i + ']').length)						
					$('select[id=' + i + ']').val(n);
			if ($('textarea[id=' + i + ']').length)
			{
					$('textarea[id=' + i + ']').val(n);
						//tinyMCE.execCommand('mceAddControl', false,i);
			}
			
			if ($('img[id=' + i + ']').length)						
				$('img[id=' + i + ']').attr('src','');
			
			if ($('img[id=' + i + ']').length)
				$('img[id=' + i + ']').attr('src',root + 'home/viewimage/' + n);
					
					
			if ($('span[id=' + i + ']').length)
				$('span[id=' + i + ']').html('');
			
			if ($('span[id=' + i + ']').length)	
				$('span[id=' + i + ']').html(n);
					
		});		
	}	
}



function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

//punches
$('#punch-in').click(function(){
	
	showLoaderSmall('#punch-in');
	$('#punch-in').attr('disabled','disabled').val('');
	
	
	var action = root + module + '/' + $("input[name='action']").val();
	dt = {is_in_or_out: 1, is_manual: 1};
	$.ajax({
	   type: 'POST',
	   url: root + 'punches/additem',
	   data: dt,
	   dataType: 'json',
	   success: function(data){
			//refresh calendar
			$('#calendar').fullCalendar('refetchEvents');
			
			hideLoaderSmall();
			$('#punch-in').val($('#punch-in').attr('title')).css('background-color','#ccc');
			$('#punch-out').removeAttr('disabled').removeAttr('style').css('punch-out');
		},
	   error: function () { onError(); hideLoader(); }
	 });
});

$('#punch-out').click(function(){
	showLoaderSmall('#punch-out');
	$('#punch-out').attr('disabled','disabled').val('');
	
	
	var action = root + module + '/' + $("input[name='action']").val();
	dt = {is_in_or_out: 0, is_manual: 1};
	$.ajax({
	   type: 'POST',
	   url: root + 'punches/additem',
	   data: dt,
	   dataType: 'json',
	   success: function(data){
			//refresh calendar
			$('#calendar').fullCalendar('refetchEvents');
			
			hideLoaderSmall();
			$('#punch-out').val($('#punch-out').attr('title')).css('background-color','#ccc');
			$('#punch-in').removeAttr('disabled').removeAttr('style').css('punch-in');			
		},
	   error: function () { onError(); hideLoader(); }
	 });
});











